package com.heihx.controller;

import com.heihx.constant.JwtClaimsConstant;
import com.heihx.dto.UserLoginDTO;
import com.heihx.entity.AddressBook;
import com.heihx.entity.Orders;
import com.heihx.entity.User;
import com.heihx.properties.JwtProperties;
import com.heihx.result.Result;
import com.heihx.service.UserService;
import com.heihx.utils.JwtUtil;
import com.heihx.vo.UserLoginVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
@Tag(name = "用户相关接口")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @Operation(summary = "微信登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("微信用户登录：{}",userLoginDTO.getCode());

        //微信登录
        User user = userService.wxLogin(userLoginDTO);

        //生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Tag(name = "根据id查询用户")
    public Result<User> getById(@PathVariable Long id){
        User user = userService.getById(id);
        return Result.success(user);
    }

    /**
     * 统计用户数量
     * @param begin
     * @param end
     * @return
     */
    @GetMapping("/countByMap")
    @Operation(summary = "统计用户")
    public Result<Long> countByMap(LocalDateTime begin, LocalDateTime end){
        Long count = userService.lambdaQuery()
                .gt(begin != null, User::getCreateTime, begin)
                .lt(end != null, User::getCreateTime, end)
                .count();
        return Result.success(count);
    }
}
